import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

export default new Vuex.Store({
  // 公共数据
  state: {
    num: 0, //购物车数量
    catadata: JSON.parse(localStorage.getItem("catid")) || [],
  },
  // 用户更变store数据
  mutations: {
    // 拿到总数
    add(state, item) {
      // console.log(item);

      // 接收总数
      state.num = item.reduce((sum, i) => {
        return (sum += i.val);
      }, 0);
    },
    catadata(state) {
      // 拿到本地的数据存起来
      localStorage.setItem("catid", JSON.stringify(state.catadata));
    },
    // 加法
    addcat(state, item) {
      // 拿到商品对应id
      let index = state.catadata.findIndex((i) => {
        return i.id == item.id;
      });
      // 如果id相等就++
      if (state.catadata[index].id == item.id) {
        state.catadata[index].val++;
      }
      // 接收总数
      state.num = state.catadata.reduce((sum, i) => {
        return (sum += i.val);
      }, 0);
      // 最新的数据加载到本地
      localStorage.setItem("catid", JSON.stringify(state.catadata));
    },
    // 减法
    subcat(state, item) {
      // state.catadata = JSON.parse(localStorage.getItem("catid"));
      // console.log(state.catadata);
      let index = state.catadata.findIndex((i) => {
        return i.id == item.id;
      });
      // console.log(index);
      // console.log(state.catadata[index].id);
      if (state.catadata[index].id == item.id) {
        // console.log(state.catadata[index].val);
        state.catadata[index].val--;
      }
      state.num = state.catadata.reduce((sum, i) => {
        return (sum += i.val);
      }, 0);

      // if (state.catadata == null) {
      //   state.catadata = [{ id, val }];
      // } else {
      //   state.catadata.push([{ id, val }]);
      // }
      localStorage.setItem("catid", JSON.stringify(state.catadata));
    },
  },
  // 处理异步数据
  actions: {},
  // 对state数据进行包装  不会改变原数据
  getters: {},
});
